package com.maxd.task;

import com.maxd.error.DescribeException;
import com.maxd.error.Result;
import com.maxd.handler.pay.IPayHandler;
import com.maxd.model.Orders;
import com.maxd.model.PayRecord;
import com.maxd.respository.PayRecordRepository;
import com.maxd.respository.selfOrder.OrdersRepository;
import com.maxd.service.selfOrder.OrdersService;
import com.maxd.service.selfWXPay.WxPayV3Service;
import com.maxd.utils.ApplicationContextUtils;
import com.maxd.utils.DateUtils;
import com.maxd.utils.JsonUtils;
import com.wechat.pay.java.service.payments.model.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Component
public class JFOrderCancelTask {

    private static final Logger log = LoggerFactory.getLogger(JFOrderCancelTask.class);
    @Autowired
    private OrdersRepository ordersRepository;

    @Autowired
    private OrdersService ordersService;

    /**
     * 每2分钟执行1次
     */
    @Scheduled(cron = "30 */2 * * * ?")
    public void jfOrderCancel() {

        Date now = new Date();
        Date startDate = DateUtils.addTime(now, Calendar.DAY_OF_MONTH, -1);
        Date endDate = DateUtils.addTime(now, Calendar.MINUTE, -30);
        String startDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, startDate);
        String endDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, endDate);

        log.info("开始扫描进行中的积分商品订单，时间范围为: {} - {}", startDateStr, endDateStr);
        List<Orders> waitPayJFOrders = ordersRepository.findWaitPayJFOrders(startDateStr, endDateStr);
        log.info("查询到取消的积分订单数量为:{}", waitPayJFOrders.size());
        for (Orders waitPayJFOrder : waitPayJFOrders) {
            log.info("积分订单取消处理，订单信息为:{}", JsonUtils.toJsonString(waitPayJFOrder));
            Result result = ordersService.orderCancel(waitPayJFOrder.getId());
            if(result.getStatus() != 0) {
                log.error("取消订单失败, orderId={}", waitPayJFOrder.getOrderNum());
            }
        }
    }


}
